package com.lb.jwitter.action;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;

import com.lb.jwitter.service.ConditionReport;
import com.lb.jwitter.service.TblCTDTDMTietHocService;
import com.lb.jwitter.service.TblCTDTThayTheMonHoc;
import com.lb.jwitter.service.TblDKMHDotDK;
import com.lb.jwitter.service.TblDKMHDotDKHocVien;
import com.lb.jwitter.service.TblDKMHDotDKHocVienService;
import com.lb.jwitter.service.TblDKMHHocVienMonHocDuocDK;
import com.lb.jwitter.service.TblDKMHHocVienMonHocDuocDKService;
import com.lb.jwitter.service.TblDKMHKetqua;
import com.lb.jwitter.service.TblDKMHKetquaService;
import com.lb.jwitter.service.TblDKMHTaiKhoanHocVien;
import com.lb.jwitter.service.TblDKMHTaiKhoanHocVienService;
import com.lb.jwitter.service.TblMenu;
import com.lb.jwitter.service.TblMenuService;
import com.lb.jwitter.service.TblQuyenChiTietService;
import com.lb.jwitter.service.TblQuyenMenu;
import com.lb.jwitter.service.TblQuyenMenuService;
import com.lb.jwitter.service.TblTaiKhoan;
import com.lb.jwitter.service.TblThongTinMonHoc;
import com.lb.jwitter.service.TblThongTinMonHocService;
import com.lb.jwitter.service.TblThongTinNhomLopMonHoc;
import com.lb.jwitter.service.TblThongTinNhomLopMonHocService;
import com.lb.jwitter.service.TblThongTinTKBChiTiet;
import com.lb.jwitter.service.TblThongTinTKBChiTietService;

import com.lb.jwitter.service.TblThongTinHocVienMonHoc;
import com.lb.jwitter.util.ApplicationContextProvider;
import com.lb.jwitter.util.CTDT;
import com.lb.jwitter.util.ChumanoLogger;
import com.lb.jwitter.util.KetQuaDangKy;
import com.lb.jwitter.util.KiemTraDangKy;
import com.lb.jwitter.util.Message;
import com.lb.jwitter.util.QuyenDangKy;
import com.lb.jwitter.util.ThoiKhoaBieuDuKien;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

@ContextConfiguration(locations = "classpath:beans.xml")
public class KiemTraDangKyAction {

	private TblDKMHTaiKhoanHocVien tblDKMHTaiKhoanHocVien;

	public TblDKMHTaiKhoanHocVien getTblDKMHTaiKhoanHocVien() {
		return tblDKMHTaiKhoanHocVien;
	}

	public void setTblDKMHTaiKhoanHocVien(
			TblDKMHTaiKhoanHocVien tblDKMHTaiKhoanHocVien) {
		this.tblDKMHTaiKhoanHocVien = tblDKMHTaiKhoanHocVien;
	}

	private Long NLMHId;

	public Long getNLMHId() {
		return NLMHId;
	}

	public void setNLMHId(Long nLMHId) {
		NLMHId = nLMHId;
	}

	// ERROR, SUCCESS, CONFIRM
	private String code;

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	private String msg;

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	private boolean trongHanDK;

	public boolean isTrongHanDK() {
		return trongHanDK;
	}

	public void setTrongHanDK(boolean trongHanDK) {
		this.trongHanDK = trongHanDK;
	}

	@Autowired
	// Injected by Spring
	ApplicationContextProvider contextProvider;

	public String execute() throws Exception {
		// tra ve ket qua
		code = "SUCCESS";
		// dang ky thanh cong
		msg = "Đăng ký thành công!!!";
		
		ChumanoLogger.init(KiemTraDangKyAction.class.getName());
		ChumanoLogger.log("0--------------KIEM TRA DANG KY--------------------");
		try{
		Map session = ActionContext.getContext().getSession();
		tblDKMHTaiKhoanHocVien = (TblDKMHTaiKhoanHocVien) session
				.get("taiKhoanHocVien");
		if (tblDKMHTaiKhoanHocVien == null)
			return "noprivilege";

		Integer dotDKId = (Integer) session.get("dotDKId");

		ApplicationContext context = contextProvider.getApplicationContext();

		TblThongTinNhomLopMonHocService tblThongTinNhomLopMonHocService = (TblThongTinNhomLopMonHocService) context
				.getBean("tbl_ThongTin_NhomLop_MonHocClient");
		TblDKMHKetquaService tblDKMHKetquaService = (TblDKMHKetquaService) context
				.getBean("tbl_DKMH_KetquaClient");
		TblThongTinTKBChiTietService tblThongTinTKBChiTietService = (TblThongTinTKBChiTietService) context
				.getBean("tbl_ThongTin_TKB_ChiTietClient");

		TblDKMHHocVienMonHocDuocDKService tblDKMHHocVienMonHocDuocDKService
		= (TblDKMHHocVienMonHocDuocDKService) context.getBean("tbl_DKMH_HocVien_MonHoc_DuocDKClient");
		
		
		TblThongTinNhomLopMonHoc nhomLopMonHoc = tblThongTinNhomLopMonHocService
				.gettblThongTinNhomLopMonHoc(new Long(NLMHId));
		trongHanDK = (Boolean) session.get("trongHanDK");
		QuyenDangKy quyenDK = (QuyenDangKy) session.get("quyenDK");
		// if (trongHanDK && quyenDK.getInsert()) {

		List<KetQuaDangKy> ketQuaDangKys = (List<KetQuaDangKy>) session.get("ketQuaDangKys");

		//-----------------------------------------------
		// Lay thong tin thoi khoa bieu chi tiet
		List<ConditionReport> cons = new ArrayList<ConditionReport>();
		{
			ConditionReport con = new ConditionReport();
			con.setCol("TKBId.id");
			con.setValue1(nhomLopMonHoc.getTKBId().getId());
			con.setOperator("eq");
			cons.add(con);
		}
		{ 
	        ConditionReport con = new ConditionReport(); 
	        con.setCol("ngayHocId.STT");
	        con.setValue1("asc");
	        con.setOperator("order");
	        cons.add(con);	
	    }
		List<TblThongTinTKBChiTiet> chiTietDKs = tblThongTinTKBChiTietService
				.findtblThongTinTKBChiTietByCondition(cons, 0, 0);

		// Tao ket qua dang ky moi
		KetQuaDangKy ketQuaDangKyNew = new KetQuaDangKy();
		// set kq
		TblDKMHKetqua ketqua = new TblDKMHKetqua();
		TblDKMHDotDK dotDK = new TblDKMHDotDK();
		dotDK.setId(new Long(dotDKId));
		ketqua.setDotDKId(dotDK);

		ketqua.setHocVienId(tblDKMHTaiKhoanHocVien.getHocVienId());
		ketqua.setNLMHId(nhomLopMonHoc);
		ketqua.setXacNhanYN(false);
		ketqua.setKhoaMonHocYN("N");

		DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
		Date dd = new Date();
		GregorianCalendar c = new GregorianCalendar();
		c.setTime(dd);
		XMLGregorianCalendar d = DatatypeFactory.newInstance()
				.newXMLGregorianCalendar(c);
		ketqua.setNgayDangKy(d);
		ketqua.setMaDieuChinh("BS");
		ketqua.setTinhTrang("RN");
		ketqua.setXacNhanYN(false);
		ketQuaDangKyNew.setKetqua(ketqua);

		// set TKB
		ThoiKhoaBieuDuKien thoiKhoaBieuDuKien = new ThoiKhoaBieuDuKien();
		thoiKhoaBieuDuKien.setNhomLop(nhomLopMonHoc);
		thoiKhoaBieuDuKien.setChiTiets(chiTietDKs);
		ketQuaDangKyNew.setThoiKhoaBieuDuKien(thoiKhoaBieuDuKien);
		// ================================================================================

		

			
	//		// ---------------------------------------------------------------------
	//		// kiem tra mon TTTN
	//		if (ketQuaDangKyNew.getKetqua().getNLMHId().getMonHocId().getLoai() != null
	//				&& ketQuaDangKyNew.getKetqua().getNLMHId().getMonHocId().getLoai().equals("TTTN")) {
	//			ChumanoLogger.log("[KIEM TRA MON TTTN]");
	//			
	//			// lay ra CTDT
	//			CTDT ctdt = (CTDT) session.get("CTDT");
	//			Message message = new Message();
	//			if (KiemTraDangKy.kiemTraKhongDuDKMonTTTN(ketQuaDangKyNew,ketQuaDangKys, ctdt, context, message)) {
	//				code = "ERROR";
	//				msg = message.getMsg();
	//				ChumanoLogger.log(msg);
	//				ChumanoLogger.stop();
	//				return Action.ERROR;
	//			}
	//
	//		}
	
	//		// -------------------------------------------------------------------
	//		// Kiem tra mon LVTN
	//		if (ketQuaDangKyNew.getKetqua().getNLMHId().getMonHocId().getLoai() != null
	//				&& ketQuaDangKyNew.getKetqua().getNLMHId().getMonHocId().getLoai().equals("LV")) {
	//			ChumanoLogger.log("[KIEM TRA MON LVTN");
	//			// lay ra CTDT
	//			CTDT ctdt = (CTDT) session.get("CTDT");
	//			Message message = new Message();
	//			if (KiemTraDangKy.kiemTraKhongDuDKMonLVTN(ketQuaDangKyNew,
	//					ketQuaDangKys, ctdt, context, message)) {
	//				code = "ERROR";
	//				msg = message.getMsg();
	//				ChumanoLogger.log(msg);
	//				ChumanoLogger.stop();
	//				return Action.ERROR;
	//			}
	//
	//		}
	
			//-----------------------------------------------
			//kiemTraThoiGianGianCachGiua2CoSo
			ChumanoLogger.log("[KIEM TRA THOI GIAN GIUA 2 CO SO");
			{
				Message message = new Message();
				if (KiemTraDangKy.kiemTraThoiGianGianCachGiua2CoSo(ketQuaDangKyNew,ketQuaDangKys, message)) {
					code = message.getCode();
					// mon hoc da dang ky
					msg = message.getMsg();
					ChumanoLogger.log(msg);
					ChumanoLogger.stop();
					return Action.ERROR;
				}
			}
			
			
			// -----------------------------------------------------------
			// kiem tra trung mon hoc
			ChumanoLogger.log("[KIEM TRA TRUNG MON HOC");
			boolean trungMonHoc = KiemTraDangKy.kiemTraTrungMonHoc(ketQuaDangKyNew,ketQuaDangKys);
			if (trungMonHoc) {
				code = "ERROR";
				// mon hoc da dang ky
				msg = "Môn học đã đăng ký!!!";
				ChumanoLogger.log(msg);
				ChumanoLogger.stop();
				return Action.ERROR;
			}
	
			// -----------------------------------------------------------
			// kiem tra trung thoi khoa bieu
			{
				ChumanoLogger.log("[KIEM TRA TRUNG TKB");
				Message message = new Message();
				boolean trungTKB = KiemTraDangKy.kiemTraTrungTKB(ketQuaDangKyNew,
						ketQuaDangKys, message);
				if (trungTKB) {
					code = "ERROR";
					// mon hoc bi trung thoi khoa bieu
					msg = message.getMsg();
					ChumanoLogger.log(msg);
					ChumanoLogger.stop();
					return Action.ERROR;
				}
			}
			// ----------------------------------------------------------------------
			// Kiem tra so tin chi dang ky toi da
			ChumanoLogger.log("[KIEM TRA SO TIN CHI DK TOI DA");
			int soTCDangKyToiDa = (Integer) session.get("soTCDangKyToiDa");
			int soTCDieuChinh = (Integer) session.get("soTCDieuChinh");
			{
				Message message = new Message();
				if (KiemTraDangKy.kiemTraVuotSoTCDangKyToiDa(ketQuaDangKyNew,ketQuaDangKys, soTCDangKyToiDa,soTCDieuChinh, context, message)) {
					code = message.getCode();
					// qua so tin chi cho phep
					msg = message.getMsg();
					ChumanoLogger.log(msg);
					ChumanoLogger.stop();
					return Action.ERROR;
				}
			}
	
			// --------------------------------------------------------------------------
			// kiem tra si so hoc vien
			{
				Message message = new Message();
				ChumanoLogger.log("[KIEM TRA SI SO LOP");
				if (KiemTraDangKy.kiemTraVuotSiSoNhomLop(ketQuaDangKyNew, message)) {
					if(message.getCode()!=null && message.getCode().equals("NOTICE1")){
						ketQuaDangKyNew.getKetqua().setKetQua("+");
						ketQuaDangKyNew.getKetqua().setKetQuaLyDo( message.getMsg());
							// tra ve ket qua notice
							code = message.getCode();
							// notice
							msg = message.getMsg();
						
					}else if(message.getCode()!=null && message.getCode().equals("NOTICE2")){
						ketQuaDangKyNew.getKetqua().setKetQua("?");
						ketQuaDangKyNew.getKetqua().setKetQuaLyDo( message.getMsg());
							// tra ve ket qua notice
							code = message.getCode();
							// notice
							msg = message.getMsg();
						
					}else {
					code = "ERROR";
					// qua si so lop cho phep
					msg = "Quá sĩ số lớp cho phép!";
					ChumanoLogger.log(msg);
					ChumanoLogger.stop();
					return Action.ERROR;
					}
				}
//				else if(message.getCode()!=null && message.getCode().equals("NOTICE")){
//					ketQuaDangKyNew.getKetqua().setKetQua("0");
//					ketQuaDangKyNew.getKetqua().setKetQuaLyDo( message.getMsg());
//						// tra ve ket qua notice
//						code = message.getCode();
//						// notice
//						msg = message.getMsg();
//					
//				}
			}
	
			// ---------------------------------------------------------------------
			// kiem tra hedao tao nhom lop
			{
				ChumanoLogger.log("[KIEM TRA HE DAO TAO - NHOM LOP");
				Message message = new Message();
				if (KiemTraDangKy.kiemTraNhomLopKhongDuocDangKy(ketQuaDangKyNew,context, message)) {
					code = "ERROR";
					msg = message.getMsg();
					ChumanoLogger.log(msg);
					ChumanoLogger.stop();
					return Action.ERROR;
				}
			}
	
			// ----------------------------------------------------------------------
			// kiem tra ngoai le nhom VIet-Phap
			// dieu kien dau vao: kiem tra sau khi kiem tra hedaotao-nhomlop
//			{
//				ChumanoLogger.log("[KIEM TRA VIET-PHAP");
//				Message message = new Message();
//				if (KiemTraDangKy.kiemTraNgoaiLe(ketQuaDangKyNew, ketQuaDangKys,message)) {
//					code = "ERROR";
//					msg = message.getMsg();
//					ChumanoLogger.log(msg);
//					ChumanoLogger.stop();
//					return Action.ERROR;
//				}
//			}
	
			// -----------------------------------------------------------
			// kiem tra mon hoc tien quyet
			//neu khong co chuyen nganh 
			//khong co he dao tao
			//hoac he dao tao la SDH
			if(ketQuaDangKyNew.getKetqua().getHocVienId().getChuyenNganhId() == null 
					|| ketQuaDangKyNew.getKetqua().getHocVienId().getHeDaoTaoId() == null
					|| ketQuaDangKyNew.getKetqua().getHocVienId().getHeDaoTaoId().getMa().equals("SDH")){
			
				//khong kiem tra mon tien quyet
			}else{
				ChumanoLogger.log("[KIEM TRA MON TIEN QUYET");
				{
					Message message = new Message();
					List<TblThongTinHocVienMonHoc> ketQuahocTaps = (List<TblThongTinHocVienMonHoc>) session.get("ketQuaHocTap");
					boolean thieuMonTienQuyet = KiemTraDangKy.kiemTraMonHocTienQuyet(ketQuaDangKyNew, ketQuaDangKys, ketQuahocTaps, context, message);
					if (!thieuMonTienQuyet) {
						code = "ERROR";
						// thieu mon hoc tien quyet,hoc truoc hoac song hanh
						msg = message.getMsg();
						ChumanoLogger.log(msg);
						ChumanoLogger.stop();
						return Action.ERROR;
					}else if(message.getCode()!=null && message.getCode().equals("NOTICE")){
						ketQuaDangKyNew.getKetqua().setKetQua("0");
						ketQuaDangKyNew.getKetqua().setKetQuaLyDo( message.getMsg());
							// tra ve ket qua notice
							code = message.getCode();
							// notice
							msg = message.getMsg();
						
					}
				}
			}
	
			// -----------------------------------------------------------
			// kiem tra mon hoc thay the
			// List<TblCTDTThayTheMonHoc> monhocthaythes =
			// KiemTraDangKy.kiemTraMonHocThayThe(ketQuaDangKyNew, context);
			// if(monhocthaythes.size()>0){
			// code = "ERROR";
			// msg = "Mon hoc duoc thay the boi: "
			// + "(<b>" + monhocthaythes.get(0).getMHThayThe1Id().getMa() + "</b>) "
			// + monhocthaythes.get(0).getMHThayThe1Id().getTen();
			//
			// return Action.ERROR;
			// }
	
			// -----------------------------------------------------------
			// kiem tra mon nhom lop
			// boolean camdangky = KiemTraDangKy.kiemTraCamNhomLop(ketQuaDangKyNew,
			// context);
			// if(!camdangky){
			// code = "ERROR";
			// msg = "Khong duoc dang ky vao nhom lop!!!";
			//
			// return Action.ERROR;
			// }
		

		ChumanoLogger.log("[-----------KIEM TRA XONG------");
		// ===========================================================
		// khong co tranh chap nao
		// them nhom lop mon hoc vao danh sach dang ky
		// them vao CSDL ketquadangky
		if (trongHanDK && quyenDK.getInsert()) {
			if(ketQuaDangKyNew.getKetqua().getKetQua() == null || ketQuaDangKyNew.getKetqua().getKetQua().equals("")){
				ketQuaDangKyNew.getKetqua().setKetQua("*");
			}
			ketQuaDangKyNew.getKetqua().setKetQua2(ketQuaDangKyNew.getKetqua().getKetQua());
			ketQuaDangKyNew.getKetqua().setKetQuaLyDo2(ketQuaDangKyNew.getKetqua().getKetQuaLyDo2());
			
			Long id = tblDKMHKetquaService.createtblDKMHKetqua(ketqua);
			ketqua.setId(id);
			ketQuaDangKyNew.getKetqua().setId(id);
			

			// them vao session
			ketQuaDangKys.add(ketQuaDangKyNew);
			session.put("ketQuaDangKys", ketQuaDangKys);

		} else {

			// them vao session
//			ketQuaDangKyNew.getKetqua().setKetQua("TA");
//			ketQuaDangKyNew.getKetqua().setKetQuaLyDo("Môn học đăng ký tạm!");
			ketQuaDangKys.add(ketQuaDangKyNew);
			session.put("ketQuaDangKys", ketQuaDangKys);

			code = "NOTICE";
			// chua den han dang ky, ket qua chi duoc luu tam, se mat khi dang
			// xuat!
			msg = "Bạn chưa đến hạn đăng ký, kết quả chỉ dùng tham khảo, sẽ bị xóa khi đăng xuất!!!";
		}
		
		ChumanoLogger.log("-------DANG KY THANH CONG-----------");
		
		}catch(Exception e){
			ChumanoLogger.log("---------------ERROR--------------");
			StringWriter errors = new StringWriter();
			e.printStackTrace(new PrintWriter(errors));
			ChumanoLogger.log(errors.toString());
			ChumanoLogger.log("==================================");
		}
		
		ChumanoLogger.stop();
		return Action.SUCCESS;

	}

}
